<?php
/**
 * 采集
 * 
 * Created	: 2011-06-11
 * Modified : 2011-06-11
 * @author  : 陈立强
 */
class Gather
{
	
	public static $info=null;
	public static $cfg = null;
	public static $cfgName = 'build/gather';
	
	/**
	 * 初始化玩家的采集信息
	 * @param int $uid
	 */
	public static function init ($uid)
	{
		global $DB, $L;
		if (!$uid) {
			return false;
		}
		
		$data = array();
		$lvl  = self::getLvl($uid);
		
		$gatherCfg = self::$cfg;
		$blockNum        = $gatherCfg[$lvl]['block_num'];

		$DB->beginTransaction();
		for ($pos=1; $pos<=$blockNum; $pos++) {
			// 更新数据
			$data = array(
				'uid'			=> $uid,
				'pos'			=> $pos,
				'status'		=> 0,
				'now_product'	=> 0,
				'harvest_time'	=> 0,
				'items'			=> '',
				'enrichment'	=> 0
			);
			$ret = $DB->insert('gather', $data);
			if (!$ret) {
				$DB->rollBack();
				break;
			}
		}

		if ($ret) {
			$DB->commit();
		}
		return $ret;
	}
	
	/**
	 * 获取一块空位的信息
	 * @param int $uid 用户ID
	 * @param int $pos 空位的位置
	 * @param int $updateInfo 是否同时更新可收获产品的信息
	 */
	public static function getPosInfo($uid, $pos, $updateInfo=1)
	{
		global $DB, $L;
		
		$sql    = 'SELECT * FROM gather WHERE uid=:uid and pos=:pos';
		$params = array('pos'=>(int)$pos, 'uid'=>(int)$uid);
		$info   = self::$info = $DB->getValue($sql, $params);
		if (false === $info) {
			return array(
				'val' => false,
				'msg' => $L['Failure']
			);
		}
		$now = time();
		if ($updateInfo 
				&& $info['harvest_time']>0 && $info['harvest_time']<=$now
		 		) {
			$ret = self::endWork($uid, $pos);
			if ($ret['val']) {
				$info['items'] = $ret['data']['items'];
			}
		}
		if (empty($info['items'])) {
			$info['items'] = array();
		} else {
			if (is_string($info['items'])) {
				$info['items'] = json_decode($info['items'], true) ;
			}
		}
		if ($info['now_product'] > 0) {
			$cfgList = C('item/gather');
			$cfg = $cfgList[$info['now_product']];
			$info['title'] = $cfg['title'];
			$info['skill_type'] = $cfg['skill_type'];
		} else {
			$info['title'] = '';
			$info['skill_type'] = '';
		}
		return $info;
	}
	
	/**
	 * 获取采集等级
	 * @param int $uid 用户ID
	 */
	public static function getLvl($uid)
	{
		global $DB;
		$sql = 'SELECT gather_lvl FROM user WHERE uid='.(int)$uid;
		return (int)$DB->getValue($sql);
	}
	
	/**
	 * 获取采集场信息
	 * @param int $uid
	 */
	public static function getInfo($uid)
	{
		global $DB, $L;
		$gatherLvl = self::getLvl($uid);
		$gather    = self::$cfg;
		
		$result['val'] = $gatherLvl!==false ? true : false;
		if ($gatherLvl !== false) {
			$result['data'] = $gather[$gatherLvl];
			$result['data']['lvl'] = $gatherLvl;
			$result['data']['gather_max_enrichment'] = $G['gather_max_enrichment'];
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_get_info', $data);
		}
		return $result;
	}
	
	/**
	 * 获取所有空位信息
	 * @param int $uid
	 * @param int $to_uid 获取他人的列表
	 */
	public static function getList($uid, $to_uid=null)
	{
		global $DB, $L, $max_plowland_num;
		
		$to_uid = (int)$to_uid;
		if ($to_uid) {
			$uid = $to_uid;
		}
		
		$sql   = 'SELECT * FROM gather WHERE uid='.(int)$uid;
		$tmpList = $DB->getList($sql);
		
		$list = array();
		$now  = time();
		
		$cfgList = C('item/gather');
		foreach($tmpList as $record) {
			if (empty($record['items']) && $record['harvest_time'] > 0 
						&& $record['harvest_time']<=$now) {
				$ret = self::endWork($uid, $record['pos']);
				if ($ret['val']) {
					$record['items'] = $ret['data']['items'];
					$record['status'] = $ret['data']['status'];
				}
			}
			if (is_string($record['items'])) {
				$record['items'] = json_decode($record['items'], true) ;
			}
			$cfg = $cfgList[$record['now_product']];
			if ($record['now_product']) {
				$record['title'] = $cfg['title'];
				$record['skill_type'] = $cfg['skill_type'];
			} else {
				$record['title'] = '';
				$record['skill_type'] = '';
			}
			$list[$record['pos']] = $record;
		}
		return array(
			'val'  => true,
			'data' => $list
//			'data' => array(
//				'list' => $list,
//				'refresh_time' => $refresh_time
//			)
		);
	}
	
	/**
	 * 采集场扩建
	 * @param int $uid
	 */
	public static function extend($uid) 
	{
		global $DB, $L;
		
		$sql = 'SELECT ticket,gather_extend_times FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		
		$cfg = C('common/need_ticket');
		if ($user['gather_extend_times'] >= $cfg['gather_max_extend']) {
			return array(
				'val' => false,
				'msg' => $L['gather_extend_time_is_max']
			);
		}
		
		$needTicket = $cfg['gather_extend_need'][$user['gather_extend_times']+1];
		// 点券不足
		if ($needTicket > $user['ticket']) {
			return array(
				'val' => false,
				'msg' => $L['ticket_not_enough']
			);
		}
		
		$DB->beginTransaction();
		// 将扩建次数加1,且扣除对应的点券
		$sql = 'UPDATE user SET ticket=ticket-'.$needTicket.',gather_extend_times=gather_extend_times+1 WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}
		
		// 增加一块空位
		if ($ret) {
			$sql = 'SELECT MAX(pos) FROM gather WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$data = array(
				'uid'			=> $uid,
				'pos'			=> $pos + 1,
				'now_product'	=> 0,
				'harvest_time'	=> 0,
				'items'			=> '',
				'enrichment'	=> 0
			);
			$ret = $DB->insert('gather', $data);
		}
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$ret = self::getList($uid);
			$result['data'] = $ret['data'];
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_extend', $data);
		}
		
		return $result;
	}
	
	/**
	 * 升级
	 * @param int $uid
	 * @return boolean 
	 */
	public static function lvlUp($uid)
	{
		global $DB, $L;
		$lvl = self::getLvl($uid);
		$nextLvl = $lvl+1;
		
		$gatherCfg = self::$cfg;
		
		// 是否已升级至满级
		end($gatherCfg);
		$maxLvl = key($gatherCfg);
		if ($nextLvl>$maxLvl) {
			return array(
				'val' => false,
				'msg' => $L['gather_is_max_lvl']
			);
		}
		
		$user = User::read($uid);
		// 需要金钱不足
		if ($user['coin'] < $gatherCfg[$lvl]['need_coin']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		// 角色等级是否满足
		if ($user['lvl'] < $gatherCfg[$lvl]['need_mc_lvl']) {
			return array(
				'val' => false,
				'msg' => $L['mc_lvl_is_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		$data = array(
			'gather_lvl' => $nextLvl
		);
		$ret = $DB->update('user', $data, 'uid='.$uid);
		
		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$gatherCfg[$lvl]['need_coin'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		$result['val'] = $ret;
		if ($ret) {
			// 增加新空位
			$data = array();
			
			$blockNum     = $gatherCfg[$lvl]['block_num'];
			$nextBlockNum = $gatherCfg[$nextLvl]['block_num'];
			
			// 添加上级之后pos到达下一次最大的数量的耕地
			$insert  = 1;
			$sql = 'SELECT MAX(pos) FROM gather WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$addPos = $nextBlockNum - $blockNum;
			for ($i=1; $i<=$addPos; $i++) {
				$pos += $i;
				// 更新数据
				$data = array(
					'uid'			=> $uid,
					'pos'			=> $pos,
					'now_product'	=> 0,
					'harvest_time'	=> 0,
					'items'			=> '',
					'enrichment'	=> 0
				);
				$ret = $DB->insert('gather', $data);
				if (!$ret) {
					$insert = 0;
					$DB->rollBack();
					$result['msg'] = $L['Failure_Insert'];
					$data = var_export($DB->errors, true);
					// 记录错误日志
					Log::save('gather_lvl_up', $data);
					break;
				}
			}
			if ($insert) {
				$DB->commit();
				$result['data'] = array(
					'lvl' => $nextLvl,
					'pos' => $posList
				);
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_lvl_up', $data);
		}
		return $result;
	}
	
	/**
	 * 开始工作
	 * @param int $uid
	 * @param int $itemId 产品ID
	 * @param int $pos
	 */
	public static function work($uid, $itemId, $pos)
	{
		global $DB, $L;
		
		$itemId = (int)$itemId;
		$pos = (int)$pos;
		
		$info = self::getPosInfo($uid, $pos, 0);
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['gather_isnot_assarted']
			);
		}
		
		//-- 对应位置的空位是否有在生产了
		if ($info['now_product']) {
			return array(
				'val' => false,
				'msg' => $L['gather_is_worked']
			);
		}
	
		$cfgList = C('item/gather');
		$cfgInfo = $cfgList[$itemId];
		
		// 配置信息
		if (is_null($cfgInfo)) {
			return array(
				'val' => false,
				'msg' => $L['no_such_gather_product']
			);
		}
		
		//-- 前置产品熟练度等级是否达到要求
		if ($cfgInfo['pre_product']) {
			$sql = 'SELECT lvl FROM user_proficiency WHERE uid='.$uid.' AND item_id='.$cfgInfo['pre_product'];
			$lvl = $DB->getValue($sql);
			if (!$lvl || $lvl < $G['pre_proficiency_lvl']) {
				return array(
					'val' => false,
					'msg' => $L['pre_product_lvl_not_enough']
				);
			}
		}
		
		//-- 金钱是否足够
		$sql = 'SELECT coin FROM user WHERE uid='.$uid;
		$coin = $DB->getValue($sql);
		// 金钱是否足够
		if ($coin < $cfgInfo['need_coin']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		
		$DB->beginTransaction();
		
		
		// 作物结束成长的时间点
		$endWorkTime = time() + $cfgInfo['work_need_time'];
		
		// 更新空位信息
		$data = array(
			'status'		=> 1,
			'now_product' => $itemId,
			'harvest_time' => $endWorkTime,
			'harvest_times' => $cfgInfo['harvest_times'],
			'items'    => '',
			'enrichment'    => 0,
		);
		$where = 'id='.$info['id'];
		$ret   = $DB->update('gather', $data, $where);
		
		// 扣除金线
		if ($ret) {
			$sql = 'UPDATE user set coin=coin-'.$cfgInfo['need_coin'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$data['harvest_time'] = $cfgInfo['work_need_time'] ;
			$result['data'] = $data + $info;
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_work', $data);
		}
		
		return $result;
	}
	
	/**
	 * 结束工作
	 * @param int $uid 用户ID
	 * @param int $pos 空位的位置
	 */
	public static function endWork($uid, $pos)
	{
		global $DB, $L, $G;
		
		$pos = (int)$pos;
		
		$now = time();
		
		if (self::$info) {
			$info = self::$info;
		} 
		
		if (!self::$info || self::$info['pos'] != $pos) {
			$info = self::getPosInfo($uid, $pos, 0);
		}
		
		// 当前空位是空闲状态
		if (empty($info['now_product'])) {
			return array(
				'val' => false,
				'msg' => $L['gather_hole_is_idle']
			);
		}
		
		// 还未到结束时间
		if ($info['harvest_time'] > $now) {
			return array(
				'val' => false,
				'msg' => $L['gather_work_not_end']
			);
		}
		// 还未到结束时间
		if ($info['items']) {
			return array(
				'val'		=> true,
				'msg'		=> $L['Success'],
				'data'		=> array(
					'items'		=> $info['items'],
					'status'	=> 2
				)
			);
		}
		
		//-- 生成采集产品
		$cfgList   = C('item/gather');
		$cfgInfo = $cfgList[$info['now_product']];
		$baseOutput = $cfgInfo['base_output'];
		$rnd = round(rand (60, 100)/100, 2);
		$enrichmentAdd = round($info['enrichment'] * $G['gather_param']);
		$output     = $baseOutput * $rnd + $enrichmentAdd;
		// 根据最终产量数量取配置结果
		$outputCfg = C('output/gather_output');
		$items = getRangeKeyValue($output, $outputCfg);
		$items = json_encode($items);
		
		
		$DB->beginTransaction();
		
		$harvest_time = $now + $cfgInfo['work_need_time'];
		$data = array(
			'harvest_time'	=> $harvest_time,
			'status'		=> 2,
			'items' 		=> $items,
		);
		$where = 'id='.$info['id'];
		$ret   = $DB->update('gather', $data, $where);
		
		// 是否有机率获取惊喜宝箱
		if ($ret && getRandResult($G['harvest_get_box_rate'])) {
			$item_id = 11006;
			$lvl = 0;
			$ret = TreasureBox::get($uid, $item_id, $lvl);
		}
		
		$result['val'] = $ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'items'	=> $items,
				'status'=> 2
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_end_work', $data);
		}
		
		return $result;
		
	}
	
	/**
	 * 收获指定果树的果实
	 * @param int $uid 用户ID
	 * @param int $pos 空位的位置
	 */
	public static function harvest($uid, $pos)
	{
		global $DB, $L, $G;
		
		$pos = (int)$pos;
		
		$now = time();
		
		$info = self::getPosInfo($uid, $pos, 1);
		
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		// 位置是空的，没有在工作
		if ($info['now_product'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['gather_hole_is_idle']
			);
		}
		
		// 未到收获时间
		if ($info['harvest_time']>$now || $info['harvest_time']==0) {
			return array(
				'val' => false,
				'msg' => $L['gather_work_not_end']
			);
		}
		
		$freeCapacity = Depot::getFreeCapacity($uid);
		// 仓库容量不足
		if ($freeCapacity == 0) {
			return array(
				'val' => false,
				'msg' => $L['not_enough_grid_in_depot']
			);
		}
		// 产品是否全部收获
		$allHarvest = ($freeCapacity >= array_sum($info['items']));
		
		//-- 收获增加富集度
		if ($allHarvest) {
			$cfg = self::$cfg;
			$lvl = self::getLvl($uid);
			$enrichment = $info['enrichment'] + rand($G['harvest_add_enrichment'][0], $G['harvest_add_enrichment'][1]);
			if ($enrichment > $G['gather_max_enrichment']) {
				$enrichment = $G['gather_max_enrichment'];
			}
		}
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		$ret = false;
		
		$gatherList = C('item/gather');
		$gatherInfo = $gatherList[$info['now_product']];
		$gatherName = $gatherInfo['title'];
		//-- 收获物品进入仓库
		$qualityCfg = $G['quality_id'];
		// 大中小各型号产品进入仓库
		$harvest = array();
		// 产品从小到大进行收获
		ksort($info['items']);
		foreach ($info['items'] as $quality => $num) {
			if ($num == 0) {
				unset($info['items'][$quality]);
				continue;
			}
			if ($freeCapacity == 0) {
				break;
			}
			if ($freeCapacity < $num) {
				$num = $freeCapacity;
				$info['items'][$quality] -= $num;
			} else {
				unset($info['items'][$quality]);
			};
			$data = array(
				'title'		=> $info['title'],
				'item_id'	=> $info['now_product'],
				'item_type' => $gatherInfo['item_type'],
				'num'		=> $num,
				'stack '	=> 1,
				'quality'	=> $quality,
				'lvl'		=> $gatherInfo['lvl']
			);
			$ret = Depot::in($uid, $data);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			}
			$harvest[$quality] = $num;
			
			// 当前收获后已经没有容量 了
			$freeCapacity -= $num;
			if ($freeCapacity == 0) {
				break;
			}
		}
		
		//-- 收获获得采集对应熟练度
		if ($ret && $allHarvest) {
			$proExp = $gatherInfo['add_proficiency'];// 获取的熟练度值
			$ret = User::addProficiency($uid, $proExp, $info['now_product'], 4);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}
		//-- 收获获得经验
		if ($ret && $allHarvest) {
			$exp = $gatherInfo['add_exp'];
			$ret = User::addExp($uid, $exp);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}
	
		
		// 是否可以获取惊喜宝箱
		if ($ret && $allHarvest && getRandResult($G['harvest_get_box_rate'])) {
			$item_id = 11006;
			$lvl = 0;
			$mailContent = sprintf($L['harvest_get_box'], $info['title']);
			$return = TreasureBox::get($uid, $item_id, $lvl, null, $mailContent);
			$ret = $return['val'];
			$inMail = $return['data']['in_mail'];
			$getTreasureBox = true;
		} else {
			$inMail = false;
			$getTreasureBox = false;
		}
		$DB->setTransactionState(true);
		
		//-- 修改采集建筑信息
		if ($ret) {
			// 全部收获清空采集地信息
			if ($allHarvest) {
				// 收获次数
				$harvest_times = $info['harvest_times'] - 1;
				if ($harvest_times <= 0) {
					$harvest_time = 0;
					$harvest_times = 0;
				} else {
					// 下次收获时间点
					$harvest_time = $now + $gatherInfo['work_need_time'];
				}
				$data = array(
					'status'		=> 1,
					'items'			=> '',
					'harvest_time'	=> $harvest_time,// 下一次收获的时间
					'enrichment'	=> $enrichment,
					'harvest_times'	=> $harvest_times
				);
			} else {
				$data = array(
					'items'	=> json_encode($info['items']),
				);
			}
			$where = 'id='.(int)$info['id'];
			$ret   = $DB->update('gather', $data, $where);
			if ($ret !== false) {
				$ret = true;
			}
		}
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = $data + $info;
			$result['data']['get_treasure_box'] = $getTreasureBox;
			$result['data']['in_mail'] = $inMail;
			$result['data']['all_harvest'] = $allHarvest;
			if (!$allHarvest) {
				$result['data']['harvest'] = $harvest;
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_harvest', $data);
		}
		
		return $result;
	}
	
	/**
	 * 获取种子列表
	 * @param $uid
	 */
	public static function getSeedList($uid)
	{
		global $DB, $L;
				
		$sql    = 'SELECT lvl,item_id FROM user_proficiency WHERE uid='.$uid.' AND class=4';
		$proficiency = $DB->getList($sql);
		
		$proList = array();
		foreach ($proficiency as $value) {
			$proList[$value['item_id']] = $value['lvl'];
		}
		
		$cfgList = C('item/gather');
		$seedCfgList = C('item/seed_list');
		
		$data = array();
		$unable = array();
		$skillNameList = C('item/skill_type_name');
		foreach ($cfgList as $item_id=>$cfg) {
			$cfg = $cfgList[$item_id];
			if ($cfg['pre_product']) {
				$proVal = isset($proList[$cfg['pre_product']]) 
							? $proList[$cfg['pre_product']]
							: 0;
			} else {
				$proVal = 1;
			}
			if ($cfg['need_proficiency_lvl'] > $proVal) {
				// 熟练度等级不够
				$enable = false;
			} else {
				$enable = true;
			}
			$data[] = array(
				'enable'	=> $enable,
				'item_id'	=> $item_id,
				'need_coin'	=> $cfg['need_coin'],
				'title'		=> $cfg['title'],
				'lvl'		=> $cfg['lvl'],
				'skill_type'=> $skillNameList[$cfg['skill_type']],
				'item_type'	=> $cfg['item_type'],
				'work_need_time' => $cfg['work_need_time']
			);
		}
		
		return array(
			'val' => true,
			'data' => $data,
		);
	}
	
	/**
	 * 清理
	 * @param int $uid 用户ID
	 * @param int $pos 位置
	 */
	public static function eradicate($uid, $pos)
	{
		global $DB, $L, $G;
		
		$DB->beginTransaction();
		
		$data = array(
			'status'		=> 0,
			'now_product'	=> 0,
			'harvest_time'	=> 0,
			'harvest_times'	=> 0,
			'items'			=> 0,
			'enrichment'	=> 0,
		);
		$pos = (int)$pos;
		$ret = $DB->update('gather', $data, 'uid='.$uid.' and pos='.$pos);
		$ret!==false && $ret = true;
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getPosInfo($uid, $pos);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('gather_harvest', $data);
		}
		return $result;
	}
	
	/********************************************
	 * 互动部分
	 ********************************************/
	
	/**
	 * 偷窃
	 * @param int $uid
	 * @param int $to_uid
	 * @param int $pos
	 */
	public static function steal($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		if ($uid == $to_uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point,in_prison');
		if ($userInfo['in_prison']) {
			$sql = 'SELECT * FROM prison WHERE uid='.$uid;
			$prisonInfo = $DB->getValue($sql);
			if (!$prisonInfo['can_interactive']) {
				return array(
					'val' => false,
					'msg' => $L['cannot_steal_in_prison']
				);
			}
		}
		
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$posInfo = self::getPosInfo($to_uid, $pos);
		// 还未成熟,不能偷窃
		if ($posInfo['status'] != 2) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经被偷过了
		if ($posInfo['is_stolen']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$toUserInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time');
		
		// 载入互动操作配置
		C('common/interactive');
		
		// 上次偷窃时间到现在超过24小时,连续偷窃次数清零
		if ($userInfo['last_steal_time'] < ($now-86400)) {
			$stealTimes = 0;
			$seriateStealParam = $G['seriate_steal_param'][0];
		} else {
			$stealTimes = $userInfo['seriate_steal_times'] + 1;
			if (isset($G['seriate_steal_param'][$userInfo['seriate_steal_times']])) {
				$seriateStealParam = $G['seriate_steal_param'][$userInfo['seriate_steal_times']];
			} else {
				$seriateStealParam = 0;
			}
		}
		
		if ($seriateStealParam) {
			$differenceLvl = abs($userInfo['lvl'] - $toUserInfo['lvl']);
			$cfgList = C('item/gather');
			$cfg = $cfgList[$posInfo['now_product']];
			$successRate = $G['base_steal_success_rate'][$cfg['lvl']]
							* $G['difference_lvl_steal_param'][$differenceLvl]
							* $G['seriate_steal_param'][$stealTimes];
			$success = getRandResult($successRate);
		} else {// 参数为0,肯定失败
			$success = false;
		}
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		$result['data'] = array(
			'success' => $success
		);
		
		if ($success) {
			$addition = 0;
			foreach ($posInfo['num'] as $quality=>$num) {
				$addition += ($num * $G['steal_coin_prize_param'][$quality]);
			}
			// 获得金钱奖励
			$getCoin = $G['steal_coin_prize_base_value'] + $addition;
			$sql = 'UPDATE user SET coin=coin+'.$getCoin.',energy_point=energy_point-1,
					seriate_steal_times='.$stealTimes.',last_steal_time='.$now.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret) {
				$result['data']['get_coin'] = $getCoin;
			}
			
			if ($ret) {
				$sql = 'UPDATE farm SET is_stolen=1 WHERE fid='.$posInfo['fid'];
				$ret = $DB->exeSql($sql);
			}
		} else {
			// 关进监狱
			$ret = Prison::detain($uid);
			
			// 扣除能量点,偷窃次数重置
			if ($ret) {
				$sql = 'UPDATE user SET energy_point=energy_point-1,
						seriate_steal_times=0,last_steal_time='.$now.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
			}
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_steal', $data);
		}
		return $result;
	}
	
	/**
	 * 维修
	 * @param $uid
	 * @param $to_uid 被维修的采集场主人用户ID
	 * @param $pos 采集场位置
	 */
	public static function maintain($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
	
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point');
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$posInfo = self::getPosInfo($to_uid, $pos);
		// 只能工作过程 才能维修
		if ($posInfo['status'] != 1) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经维修过
		if ($posInfo['is_maintained']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		// 载入互动操作配置
		C('common/interactive');
		
		$cfgList = C('item/gather');
		$cfg = $cfgList[$posInfo['now_product']];
		// 减少时间
		$reduceTime = round($cfg['work_need_time'] * $G['maintain_reduce_time']);
		$sql = 'UPDATE gather SET is_maintained=1,harvest_time=harvest_time-'.$reduceTime.' WHERE fid='.$posInfo['fid'];
		$ret = $DB->exeSql($sql);
		
		// 扣除能量点
		if ($ret) {
			$sql = 'UPDATE user SET energy_point=energy_point-1 WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		// 增加经验
		if ($ret) {
			$ret = User::addExp($uid, $G['maintain_get_exp']);
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getPosInfo($to_uid, $pos);
			$result['data'] = array(
				'get_exp'	=> $G['maintain_get_exp']
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_weed', $data);
		}
		return $result;
	}
}





